import * as excel from './excel'


export type Role='Visitor'|'Reader'|'BookManager'|'UserManager'|'SuperManager'|undefined

export interface User{
    id:number,
    name?:string
    nickName:string,
    role:Role
    token?:number
    [x:string]:any
}

export interface NewUser{
    name:string,
    nickName:string,
    password:string,
    role:Role,
}

export interface ImportOptions{
    skipHeader:boolean,
    nameCol:string
    nickNameCol:string
    passwordCol:string
    file:File
    role:Role
}

export const Visitor:User={
    id:-1,
    nickName:'访客',
    role:'Visitor',
}

export const FakeSuper:User={
    id:9999,
    nickName:'super',
    role:'SuperManager',
}



export const user_template_url='api/user/add/template'

export async function try_post_new_user(user:NewUser){
    const api='/api/user/add'
    const res =await fetch(api,{
        method:'post',
        body:JSON.stringify(user),
        headers:{'Content-Type':'application/json;charset=utf-8'}
    })
    if (res.ok==false) {
        throw await res.text()
    }
    
}

export async function try_parse_users_from_excel(options:Partial<ImportOptions>){
    console.log('User Import options:',options)
    let sheet:any
    try {
        sheet= await excel.try_get_sheet(options.file!)
    } catch (error) {
        throw '读取工作表失败!'
    }
    // console.dir(sheet)
    let row_idx=options.skipHeader?2:1
    const new_users:NewUser[]=[]
    // console.log('has row:',row_idx,has_row(sheet,row_idx))
    while (excel.has_row(sheet,row_idx)) {
        const new_user:NewUser=Object.create(null)

        new_user.name=excel.read_cell(sheet,row_idx,options.nameCol)
        if (!new_user.name) {
            throw `读取用户姓名失败, 行号[${row_idx}]`
        }

        new_user.nickName=excel.read_cell(sheet,row_idx,options.nickNameCol)
        if (!new_user.nickName) {
            throw `读取用户昵称失败, 行号[${row_idx}]`
        }
    
        new_user.password=excel.read_cell(sheet,row_idx,options.passwordCol)
        if (!new_user.password) {
            throw `读取用户密码失败, 行号[${row_idx}]`
        }
        if (!options.role) {
            throw `未设置用户角色!`
        }
        new_user.role=options.role
        new_users.push(new_user)
        row_idx++
    }
    return new_users
}
interface ImportResult{
    acceptCount:number
    repeatCount:number
    importCount:number
    message:string
}

export async function try_post_new_users(users:NewUser[]) {
    const api='/api/user/import'
    // console.dir(users)
    // console.log(JSON.stringify(users))
    const res =await fetch(api,{
        method:'post',
        body:JSON.stringify(users),
        headers:{'Content-Type':'application/json;charset=utf-8'}
    })
    if (res.ok==false) {
        console.error('Import new users failed!')
        // console.dir(res)
        const error= await res.text()
        throw error
    }
    return (await res.json() as ImportResult)
}

export async function try_get_users(role:Role=undefined){
    let api='/api/user/all'
    if (role) {
        api=`${api}?role=${role}`;
    }
    const res= await fetch(api)
    if (res.ok==false) {
        throw await res.text()
    }
    return await res.json() as User[]
}

export async function try_delete_user(uid:number){
    const api='/api/user/delete/'+uid
    const res= await fetch(api,{
        method:'delete'
    })
    if(!res.ok){
        throw await res.text()
    }
    return (await res.json() ) as User
}